package com.code.aspectj.aspectj;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.code.aspectj.AppInterceptor;
import com.code.aspectj.annotation.Network;
import com.code.aspectj.util.NetworkUtils;
import com.code.aspectj.util.P;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;

import static com.code.aspectj.AppInterceptor.TAG;

/**
 * Created by RLZ
 * on 2022/1/6
 */
@Aspect
public class NetAspect {

    @Pointcut("execution(@com.code.aspectj.annotation.Network * *(..))")
    public void pointcutCheckNetwork() {

    }

    @Around("pointcutCheckNetwork()")
    public Object aroundCheckNetwork(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Network checkNetwork = signature.getMethod().getAnnotation(Network.class);
        if (checkNetwork == null) return null;
        String tip = checkNetwork.tips();
        if (NetworkUtils.isConnected()) {
            P.e(TAG, joinPoint.getArgs().getClass().getSimpleName() + " 检查网络已连接 ");
            joinPoint.proceed();
        } else {
            if (AppInterceptor.getContext() == null) return null;
            Toast.makeText(AppInterceptor.getContext(), tip, Toast.LENGTH_SHORT).show();
        }
        return null;
    }
}
